<?php

require_once 'classes/LightPressPlugin.php';

class PageTemplates extends LightPressPlugin {

    var $default_context = LP_CONTEXT_STATIC;
    var $active = true;
    var $hooks = array('start_render');

    var $description = 'Allows pages to use individual templates (like in WordPress).  Template names are read from the ';
    var $constructor_args = array('template_meta_key' => 'meta key where page template is stored (WordPress uses "_wp_page_template")');
    
    var $template_meta_key = '_wp_page_template';
    
    var $_frontend;

    function PageTemplats(&$frontend, $args, $dummy_run=false) {
		$this->LightPressPlugin($frontend, $args, $dummy_run);
    }
    
    function hide() {
    }

    function run($hook, &$templates) {
		if (!$this->active)
			return;
        $f =& $this->_frontend;
        
        // only valid for pages or single posts
        if (($f->context['type'] == 'static') || ($f->context['type'] == 'post')) {
		
            // retrieve page styles
            $qry = "SELECT DISTINCT m.post_id, m.meta_key, m.meta_value " .
                "FROM {$f->tables['postmeta']} m, {$f->tables['posts']} p " .
                "WHERE p.ID = m.post_id " .
                " AND " . ($f->context['type'] == 'static' ? 'p.id' : 'p.name') . "= '{$f->context['filter']}' " .
                "AND meta_key='{$this->template_meta_key}' ";
            $f->db->query($qry);
            
            foreach ($f->db->all() as $meta) {
                if (!empty($meta['meta_value']) && ($meta['meta_value'] != 'default'))
                    $templates['index'] = str_replace('.php', '.xml', $meta['meta_value']);
            }
        }
        $this->active = false;
        return;
	}
}

?>